// 创建一个闭包
(function($) {
	//服务器上传路径
	var fileuploadServerUrl = base + "/admin/attach/upload";
	//swf文件路径
	var swfFileuploadUrl = base + "/static/webuploader/Uploader.swf";
	var fileBasePath = base + "/";
	
	// 插件的定义
	$.fn.fileupload = function(options) {
		var $ = jQuery;
		var $this = $(this);
		var uploaderId = $this.attr("id");
		var pickerBtnId = uploaderId + "-picker";
		var pickerHideBtnId = uploaderId + "-picker-hide";
		var startUploadBtnId = uploaderId + "-ctlBtn";
		var fileListId = uploaderId + "-thelist";
		
		var singleFile = (options.fileNum && options.fileNum == 1);
		
		if(!options){
			options = {auth:true,disable:false};
		}
		var sUrl;
		if(options.auth){
			sUrl = fileuploadServerUrl + "?auth=true";
		}else{
			sUrl = fileuploadServerUrl + "?auth=false";
		}
		
		var opt = $.extend({
			// 不压缩image
			resize : false,

			// swf文件路径
			swf : swfFileuploadUrl,

			// 文件接收服务端。
			server : sUrl

			// 选择文件的按钮。可选。
			// 内部根据当前运行是创建，可能是input元素，也可能是flash.
			// ,pick: '#' + pickerBtnId
			,
			pick : {
				id : "#" + pickerHideBtnId,
				label : "上传"
			},
			//
			fileSingleSizeLimit:50*1024*1024,
			auto:true
		}, options);

		if(options.imgType){
			opt.accept = {
	            title: 'Images',
	            extensions: 'gif,jpg,jpeg,bmp,png',
	            mimeTypes: 'image/*'
	        };
		}
		
		var id = $this.attr("id");
		var successFun = options.success;
		var errorFun = options.error;

		var uploderHtml = '';
		
		//如果是图片
		if(options.imgType){
			var userPicStyle1 = "";
			var userPicStyle2 = "";
			if(options.userPic){
				userPicStyle1 = "border-width:0";
				userPicStyle2 = "margin: auto;float: none;margin-top: 80px;";
			}
			uploderHtml = '<div class="jzupload" style="' +userPicStyle1+ '"><div id="'
				+ fileListId
				+ '" class="filelists jzuploadfl">'
				+ '</div>'
				+ '<a id="'
				+ pickerBtnId
				+ '"title="点击添加文件" class="fileAddBtn jzuploadfl" style="' +userPicStyle2+ '"></a><div class="clear"></div>'
				+ '<a  id="'
				+ pickerHideBtnId
				+ '" style="display:none"></div>'
				;
			
		}else{
				uploderHtml = '<div class="jzupload">'
					+ '<div id="'
					+ fileListId ;
					if(singleFile){
						uploderHtml = uploderHtml	+ '" class="filelists jzuploadfl"></div>';
					}else{
						uploderHtml = uploderHtml	+ '" class="filelists"></div>';
					}
					uploderHtml = uploderHtml + '<a  id="'
					+ pickerHideBtnId
					+ '" style="display:none"></a><a id="'
					+ pickerBtnId
					+ '" title="点击添加文件" class="fileAddBtntxt jzuploadfl">选择文件</a><div class="clear"></div>';
				if(!opt.auto){
					uploderHtml = uploderHtml	+ '<a id="'
					+ startUploadBtnId
					+ '" title="点击添加文件" class="fileAddBtntxt grays jzuploadfl">开始上传</a>';
				}
				
		}
		
		uploderHtml = uploderHtml + '<div class="fileitemclear"></div></div>';
		
		jQuery("#" + uploaderId).append(uploderHtml);

		$("#" + pickerBtnId)
				.on(
						"click",
						function() {
							triggerOpenFile(options,pickerHideBtnId);
						});

		var $list = $('#' + fileListId), $btn = $('#' + startUploadBtnId), state = 'pending', uploader;
		uploader = WebUploader.create(opt);
		uploader.files = {};
		
		//数据回显
		if(options.fileList){
			var fileList = options.fileList;
			for (i = 0; i < fileList.length; i++) {
				var file = fileList[i];
				var fileid = "already_" + i;
				//如果是图片
				if(options.imgType){
					var fileurl = "";
					if(file.url.indexOf("http://") == 0){
						fileurl = file.url;
					}else{
						fileurl = fileBasePath + file.url;
					}
					var sty = "";
					if(options.userPic){
						sty = ' width:auto;height:auto;';
					}
					var closeHtml = "";
					if(!options.disable){
						closeHtml = '<span class="close" id="del' +fileid+ '" rowid="' +fileid+ '">-</span>';
					}
					var userPicStyle1 = "";
					if(options.userPic){
						userPicStyle1 = "border:0;margin-right:0;";
					}
					$list.append(''
							+ '<a id="' + fileid + '" class="fileitem" href="javascript:;" style="'+sty+ userPicStyle1 + '">'
							+ '<div class="fimg"><img title="' +file.name+ '" src="' + fileurl+ '" id="img' +fileid+ '" durl="' +file.url+ '"/></div>'
							+ closeHtml
							+ '<span class="status success"></span>'
							+ '</a>');
				}else{
					$list.append('<div id="' + fileid + '" class="fileitembox">'
							+ '<img style="margin-top:5px" class="jzuploaddel" src="'+base+'/static/res/common/img/del.png" id="del' +fileid+ '" rowid="' +fileid+ '"/>'
							+ '<a class="fileitem txt" href="javascript:;" id="img' +fileid+ '"  durl="' +file.url+ '">  '
							+ file.name + '</a>'
							+ '<p class="fileitem_tip">&nbsp;</p><div style="clear: both;"></div></div>');
				}
				uploader.files[fileid] = {};
				uploader.files[fileid]["name"] = file.name;
				uploader.files[fileid]["url"] = file.url;
				try {
					uploader.files[fileid]["relativeUrl"] = file.relativeUrl;
				} catch (e) {
				}
				
				if(!options.disable){
					if(options.userPic){
						$("#" + pickerBtnId).hide();
						$("#img" + fileid).on("click", function(){
							triggerOpenFile(options,pickerHideBtnId);
						});
						$("#del" + fileid).on("click", function(){
							debugger
							$("#" + $(this).attr("rowid")).remove();
							delete uploader.files[fileid];
							$("#" + pickerBtnId).show();
						});
					}else{
						$("#img" + fileid).on("click", function(){
							var durl = $(this).attr("durl");
							if(durl.indexOf("http://") == 0){
								window.open($(this).attr("durl"));
							}else{
								window.open(fileBasePath + $(this).attr("durl"));
							}
						});
						$("#del" + fileid).on("click", function(){
							debugger
							$("#" + $(this).attr("rowid")).remove();
							delete uploader.files[fileid];
						});
					}
				}
			}
		}

		// 当有文件添加进来的时候
		uploader.on('fileQueued', function(file) {
			if(singleFile){
				$list.html("");
				uploader.files = {};
			}
			
			if(options.imgType){
				var sty = "";
				if(options.userPic){
					sty = ' width:auto;height:auto;';
				}
				var userPicStyle1 = "";
				if(options.userPic){
					userPicStyle1 = "border:0;margin-right:0;";
				}
				$list.append(''
						+ '<a id="' + file.id + '" class="fileitem" href="javascript:;" style="' +sty+ userPicStyle1+'">'
						+ '<div class="fimg"><img title="' +file.name+ '" src="" id="img' +file.__hash+ '" durl=""/></div>'
						+ '<span class="close" id="del' +file.__hash+ '">-</span>'
						+ '<span class="status success"></span>'
						+ '</a>');
			}else{
				$list.append('<div id="' + file.id + '" class="fileitembox">'
						+ '<img class="jzuploaddel"  style="margin-top:5px" src="'+base+'/static/res/common/img/del.png" id="del' +file.__hash+ '" />'
						+ '<a class="fileitem txt" href="javascript:;" durl="" id="img' +file.__hash+ '" >  '
						+ file.name + '</a>'
						+ '<p class="fileitem_tip">等待上传...</p>' + '<div style="clear: both;"></div></div>');
			}
			
			if(options.userPic){
				$("#img" + file.__hash).on("click", function(){
					triggerOpenFile(options,pickerHideBtnId);
				});
			}else{
				$("#img" + file.__hash).on("click", function(){
					if($(this).attr("durl") != ""){
						window.open(fileBasePath + $(this).attr("durl"));
					}
				});
				
			}
			$("#del" + file.__hash).on("click", function(){
				$("#" + file.id).remove();
				uploader.removeFile(file);
				delete uploader.files[file.__hash];
				if(!options.disable && options.userPic){
					$("#" + pickerBtnId).show();
				}
			});
		});

		// 文件上传过程中创建进度条实时显示。
		uploader
				.on(
						'uploadProgress',
						function(file, percentage) {
							var $li = $('#' + file.id), $percent = $li
									.find('.progress .progress-bar');

							// 避免重复创建
							if (!$percent.length) {
								$percent = $(
										'<div class="progress progress-striped active">'
												+ '<div class="progress-bar" role="progressbar" style="width: 0%">'
												+ '</div>' + '</div>')
										.appendTo($li).find('.progress-bar');
							}

							$li.find('p.fileitem_tip').text('上传中');

							$percent.css('width', percentage * 100 + '%');
						});

		uploader.on('uploadSuccess', function(file, response) {
			$('#' + file.id).find('p.fileitem_tip').text('上传成功');
			uploader.files[file.__hash] = response.data;
			$("#img" + file.__hash).attr("durl", response.data.url);
			if(response.data.url.indexOf("http://") == 0){
				$("#img" + file.__hash).attr("src", response.data.url);
			}else{
				fileurl = fileBasePath + file.url;
				$("#img" + file.__hash).attr("src", fileBasePath + response.data.url);
			}
			if(successFun != undefined){
				successFun(file, response);
			}
			
			if(singleFile){
				$("#" + pickerBtnId).hide();
			}
		});

		uploader.on('uploadError', function(file, response) {
			$('#' + file.id).find('p.fileitem_tip').text('上传出错');
			if(errorFun != undefined){
				errorFun(file, response);
			}
		});

		uploader.on('uploadComplete', function(file) {
			$('#' + file.id).find('.progress').fadeOut();
		});

		uploader.on('all', function(type) {
			if (type === 'startUpload') {
				state = 'uploading';
			} else if (type === 'stopUpload') {
				state = 'paused';
			} else if (type === 'uploadFinished') {
				state = 'done';
			}

			if (state === 'uploading') {
				$btn.text('暂停上传');
			} else {
				$btn.text('开始上传');
			}
		});
		
		$btn.on('click', function() {
			if (state === 'uploading') {
				uploader.stop();
			} else {
				uploader.upload();
			}
		});
		
		uploader.getFiles = function(returnObj){
			var ff = [];
			$.each(uploader.files, function(a1,a2){
				ff.push(a2);
			});
			if(returnObj){
				return ff;
			}else{
				return JSON.stringify(ff);
			}
		}
		
		return uploader;
	};
	
	function triggerOpenFile(options,pickerHideBtnId){
		if(!options.disable){
//			alert($("#" + pickerHideBtnId).html());
			$("#" + pickerHideBtnId + " .webuploader-element-invisible").trigger("click");
		}
	}

})(jQuery);// 闭包结束
